#include <iostream>
#include "protocol.hpp"
#include <string>
#include <strings.h>
#include <cerrno>
#include <cstring>
#include <cstdlib>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <memory>

namespace Server
{
    using namespace std;

    static const string defaultIp = "0.0.0.0";
    static const int gnum = 1024;

    class udpServer
    {
    public:
        udpServer(const uint16_t &port, const string &ip = defaultIp)
            : _port(port), _ip(ip), _sockfd(-1)
        {
        }
        void initServer()
        {
            // 1. 创建socket
            _sockfd = socket(AF_INET, SOCK_DGRAM, 0);
            if (_sockfd == -1)
            {
                cerr << "socket error: " << errno << " : " << strerror(errno) << endl;
                exit(-1);
            }
            cout << "socket success: "
                 << " : " << _sockfd << endl;

            // 2. 绑定port，ip
            struct sockaddr_in local;
            bzero(&local, sizeof(local));//memset设置全0
            local.sin_family = AF_INET;
            local.sin_port = htons(_port);
            // local.sin_addr.s_addr = inet_addr(_ip.c_str());
            local.sin_addr.s_addr = htonl(INADDR_ANY);
            int n = bind(_sockfd, (struct sockaddr *)&local, sizeof(local));
            if (n == -1)
            {
                cerr << "bind error: " << errno << " : " << strerror(errno) << endl;
                exit(-1);
            }
        }
        void start()
        {
            for (;;)
            {
                // 读取数据
                char buffer[gnum];
                struct sockaddr_in peer;
                socklen_t len = sizeof(peer);
                // ssize_t r = recv(_sockfd, buffer, sizeof(buffer)-1, 0);
                string inbuffer;
                while(1)
                {
                    string req_text, req_str;
                    if(!recvPackage(_sockfd, inbuffer, &req_text))
                        continue;
                    cout << "带报头的请求-> " << req_text << endl;
                    if(!deLength(req_text, &req_str))
                        continue;
                    cout << "去掉报头的请求-> " << req_text << endl;

                    Request req;
                    if(!req.deserialize(req_str))
                        return;
                    
                    Response res;
                    //将req处理的结果放入res

                    string res_str;
                    res.serialize(&res_str);
                    cout << "序列化完成-> " << res_str << endl;

                    string send_str = enLength(res_str);
                    cout << "构建完整的响应报文" << send_str << endl;

                    send(_sockfd, send_str.c_str(), send_str.size(), 0);
                }
            }
        }
        ~udpServer()
        {
        }

    private:
        uint16_t _port;
        string _ip;
        int _sockfd;
    };
}
